<?php

namespace ApigilityActivity\Service;

use ApigilityAddress\Service\AddressService;
use ApigilityCatworkFoundation\Base\ApigilityEventAwareObject;
use ApigilityActivity\DoctrineEntity\Activity;
use Zend\EventManager\EventManagerAwareInterface;
use Zend\ServiceManager\ServiceManager;
use Zend\Hydrator\ClassMethods as ClassMethodsHydrator;
use Zend\Hydrator\ObjectProperty as ObjectPropertyHydrator;
use Doctrine\ORM\QueryBuilder;
use Doctrine\ORM\Tools\Pagination\Paginator as DoctrineToolPaginator;
use DoctrineORMModule\Paginator\Adapter\DoctrinePaginator as DoctrinePaginatorAdapter;
use Doctrine\ORM\Query\Expr;

class ActivityService extends ApigilityEventAwareObject
{
    const EVENT_Activity_CREATED = 'ActivityService.EventActivityCreated';
    const EVENT_Activity_NICKNAME_UPDATE = 'ActivityService.EVENT_Activity_NICKNAME_UPDATE';

    protected $em;
    protected $classMethodsHydrator;
    protected $objectPropertyHydrator;

    /**
     * @var \ZF\MvcAuth\Identity\AuthenticatedIdentity
     */
    protected $authIdentity;

    protected $services;

    /**
     * @var IdentityService
     */
    protected $identityService;

    /**
     * @var OccupationService
     */
    protected $occupationService;

    /**
     * @var IncomeLevelService
     */
    protected $incomeLevelService;

    /**
     * @var AddressService
     */
    protected $addressService;

    public function __construct(ServiceManager $services)
    {

        $this->services = $services;
        $this->em = $services->get('Doctrine\ORM\EntityManager');
        $this->identityService = $services->get('ApigilityUser\Service\IdentityService');
       // $this->occupationService = $services->get('ApigilityActivity\Service\OccupationService');
       // $this->incomeLevelService = $services->get('ApigilityActivity\Service\IncomeLevelService');
        $this->addressService = $services->get('ApigilityAddress\Service\AddressService');
        $this->classMethodsHydrator = new ClassMethodsHydrator();
        $this->objectPropertyHydrator = new ObjectPropertyHydrator();

    }

    /**
     * 获取活动列表
     *
     * @param $params
     * @return DoctrinePaginatorAdapter
     */
    public function getActivitys($params)
    {
        $qb = new QueryBuilder($this->em);
        $qb->select('b')->from('ApigilityActivity\DoctrineEntity\Activity', 'b')->orderBy(new Expr\OrderBy('b.id', 'DESC'));

        $where = null;
        if (isset($params->position_id)) {
            $qb->innerJoin('b.positions', 'p');
            if (!empty($where)) $where .= ' AND ';
            $where = 'p.id = :position_id';
        }

        if (!empty($where)) {
            $qb->where($where);
            if (isset($params->position_id)) $qb->setParameter('position_id', $params->position_id);
        }

        $doctrine_paginator = new DoctrineToolPaginator($qb->getQuery());
        return new DoctrinePaginatorAdapter($doctrine_paginator);
    }


    /**
     * 创建一个活动
     * @param $data
     * @return Activity
     */
    public function createActivity($data)
    {
        $Activity = new Activity();
        
        $this->hydrateActivityData($Activity, $data);
        if (isset($data->address)) $Activity->setAddress($data->address);

        $this->em->persist($Activity);
        $this->em->flush();

        $this->getEventManager()->trigger(self::EVENT_Activity_CREATED, $this, ['Activity' => $Activity]);

        return $Activity;
    }

    /**
     * 获取单个活动信息
     *
     * @param $Activity_id
     * @return \ApigilityActivity\DoctrineEntity\Activity
     * @throws Exception\ActivityNotExistException
     */
    public function getActivity($Activity_id)
    {
        $Activity = $this->em->find('ApigilityActivity\DoctrineEntity\Activity', $Activity_id);
        if (empty($Activity)) throw new Exception\ActivityNotExistException();
        return $Activity;
    }

    /**
     * 更新单个活动信息
     *
     * @param $Activity_id
     * @param $data
     * @return Activity
     */
    public function updateActivity($Activity_id, $data)
    {
        $Activity = $this->getActivity($Activity_id);

        $this->hydrateActivityData($Activity, $data);

        $this->em->flush();

        if (isset($data->title)) {
            // 触发事件
            $this->getEventManager()->trigger(self::EVENT_Activity_NICKNAME_UPDATE, $this, ['Activity' => $Activity]);
        }

        return $Activity;
    }

    /**
     * 获取已登录的活动对象
     * @return \ApigilityActivity\DoctrineEntity\Activity
     */
    public function getAuthActivity()
    {
        $this->authIdentity = $this->services->get('api-identity');
        return  $this->getActivity($this->authIdentity->getRoleId());
    }

    /**
     * @param Activity $Activity
     * @param $data
     */
    private function hydrateActivityData(Activity $Activity, $data)
    {
        if (isset($data->title)) $Activity->setTitle($data->title);
        if (isset($data->age_to)) $Activity->setAgeTo($data->age_to);
        if (isset($data->age_from)) $Activity->setAgeFrom($data->age_from);
        if (isset($data->address)) $Activity->setAddress($data->address);
        if (isset($data->man_num)) $Activity->setManNum($data->man_num);
        if (isset($data->woman_num)) $Activity->setWomanNum($data->woman_num);
        if (isset($data->item)) $Activity->setItem($data->item);
        if (isset($data->date)) $Activity->setDate($data->date);
        if (isset($data->district_region_id)) $Activity->setdistrictRegionId($data->district_region_id);
        if (isset($data->city_region_id)) $Activity->setcityRegionId($data->city_region_id);
        if (isset($data->province_region_id)) $Activity->setprovinceRegionId($data->province_region_id);
        if (isset($data->today_where)) $Activity->settodayWhere($data->today_where);
        $Activity->added_time = time();
        /*
        if (isset($data->birthday)) {
            $datetime = new \DateTime();
            $datetime->setTimestamp($data->birthday);
            $Activity->setBirthday($datetime);
        }
        */
    }
}